package com.leadingsoft.pwxk.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.leadingsoft.plat.model.Department;
import com.leadingsoft.plat.model.Department.Type;
import com.leadingsoft.plat.repository.DepartmentRepository;
import com.leadingsoft.plat.services.DepartmentService;
import com.leadingsoft.pwxk.service.MappingOrgService;

@Service
public class MappingOrgServiceImpl implements MappingOrgService {

	@Autowired
	private DepartmentRepository repository;
	@Autowired
	private DepartmentService service;

	@Override
	public List<JSONObject> listByParentId(Long parentId) {
		List<Department> list = repository.findByParentId(parentId);
		return this.Converter(list);
	}

	@Override
	public JSONObject getFirst() {
		Optional<Department> optional = service.getFirst();
		return this.Converter(optional);
	}

	private List<JSONObject> Converter(List<Department> depts) {
		List<JSONObject> list = new ArrayList<>();
		depts.forEach(dept -> {
			list.add(this.dept2JsonStr(dept));
		});
		return list;
	}

	private JSONObject Converter(Optional<Department> optional) {
		if (optional.isPresent())
			return this.dept2JsonStr(optional.get());
		return null;
	}

	private JSONObject dept2JsonStr(Department dept) {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("id",dept.getId());
		jsonObject.put("text",dept.getFullname());
		jsonObject.put("orgCode","");
		jsonObject.put("purpose",Type.ORGANS.equals(dept.getType()) ? "1" : "2");
		jsonObject.put("parentDeptId",dept.getParent() == null ? "" : dept.getParent().getId());
		jsonObject.put("leaf",true);
		jsonObject.put("expanded",true);
		return jsonObject;
	}

}
